package com.shuai.api_platform.controller;

import com.shuai.api_platform.common.BaseResponse;
import com.shuai.api_platform.service.FileService;
import com.shuai.api_platform.utils.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    @Autowired
    private FileService fileService;


    /**
     * 文件的上传
     *
     * @param file 上传的文件
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public BaseResponse<Map<String, Object>> uploadFile(@RequestPart("file") MultipartFile file) throws IOException {
        HashMap<String, Object> response = new HashMap<>();
        if (file == null
                || file.getSize() <= 0) {
            log.error("上传文件【{}】参数错误", file);
            throw new IOException("上传文件失败，文件格式错误");
        }
        String storageName = fileService.uploadFile(file);
        response.put("storageName", storageName);
        return ResultUtils.success(response);   // 文件上传成功！
    }

    /**
     * 文件下载
     *
     * @param storageName 下载文件的名称
     * @param response    用户的输出流
     */
    @RequestMapping(value = "/download", method = RequestMethod.POST)
    public void downloadFile(String storageName, HttpServletResponse response) throws IOException {
        // 用户身份权限校验

        if (StringUtils.isBlank(storageName)) {
            log.error(LocalDateTime.now() + "异常的存储图表名称" + storageName);
            throw new IOException("异常的图表存储名称");
        }

        response.addHeader("Content-Disposition", "attachment;filename=" + storageName);
        fileService.downLoadFile(response, storageName);
        log.info("用户下载了文件【{}】", storageName);
    }

}
